import { Controller, Get, Post, Body, Query, Session, Req } from '@nestjs/common';
import { MessageTemplateService } from './message-template.service';

@Controller('messageTemplate')
export class MessageTemplateController {
  constructor(private readonly messageTemplateService: MessageTemplateService) { }

  @Get('getMessageTemplates')
  async findAll(@Session() session: Record<string, any>) {
    console.log('获取消息模板，用户ID:', session.userId);

    try {
      // 如果用户已登录，获取该用户的模板
      const userId = session.userId;
      const templates = await this.messageTemplateService.findAll(userId);

      return {
        code: 0,
        data: templates,
        msg: 'success'
      };
    } catch (error) {
      console.error('获取消息模板失败:', error);
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('createMessageTemplate')
  async create(@Body() createTemplateDto: any, @Session() session: Record<string, any>) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      createTemplateDto.userId = session.userId;
      const template = await this.messageTemplateService.create(createTemplateDto);
      return {
        code: 0,
        data: template,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('updateMessageTemplate')
  async update(@Body() updateTemplateDto: any, @Session() session: Record<string, any>) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      const { id, ...templateData } = updateTemplateDto;
      const template = await this.messageTemplateService.update(id, templateData);
      return {
        code: 0,
        data: template,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('removeMessageTemplate')
  async remove(@Body() body: { id: number }, @Session() session: Record<string, any>) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      await this.messageTemplateService.remove(body.id);
      return {
        code: 0,
        data: null,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }
} 